package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Menu;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.ulits.DateUtils;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统计数据控制层
 *
 * @author ：zengjie
 * @date ：2020/11/17
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    /**
     * 会员数量统计
     *
     * @return
     */
    @RequestMapping(value = "/getMemberReport", method = RequestMethod.GET)
    public Result getMemberReport() {
        try {
            Map map = memberService.getMemberReport();
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    /**
     * 套餐数据饼图占比
     */
    @RequestMapping(value = "/getSetmealReport", method = RequestMethod.GET)
    public Result getSetmealReport() {
        try {
            Map map = setmealService.getSetmealReport();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }


    /**
     * 会员性别，年龄占比饼图
     */
    @RequestMapping(value = "/getSetmealComposedReport", method = RequestMethod.GET)
    public Result getSetmealComposedReport() {
        try {
            List<Map> mapList = memberService.getMemberComposedReport();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, mapList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 运营数据
     */
    @RequestMapping(value = "/getBusinessReportData", method = RequestMethod.GET)
    public Result getBusinessReportData() {
        try {
            Map map = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 下载运营数据excel报表
     * 自己注入数据版
     */
    //@RequestMapping(value = "/exportBusinessReport", method = RequestMethod.GET)
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map result = reportService.getBusinessReportData();
            //获取excel模板需要的数据
            //当前日期
            String reportDate = (String)result.get("reportDate");
            //今日新增会员数
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            //总会员数
            Integer totalMember = (Integer) result.get("totalMember");
            //本周新增会员数
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            //本月新增会员数
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            //今日预约数
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            //今日到诊数
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            //本周预约数
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            //本周到诊数
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            //本月预约数
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            //本月到诊数
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            //热门套餐
            List<Map> hotSetmeal =(List<Map>)result.get("hotSetmeal");

            // 模板文件的路径
            String templatePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //创建excel对象
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(new File(templatePath)));
            //获取工作表
            XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
            //获取行
            XSSFRow row = sheet.getRow(2);
            //获取指定列对象
            XSSFCell cell = row.getCell(5);
            //往单元格设置数据
            cell.setCellValue(reportDate);
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            //遍历套餐列表数据
            int rownum = 12;//从13行开始遍历数据
            if(hotSetmeal !=null && hotSetmeal.size()>0){
                for (Map hsMap : hotSetmeal) {
                    XSSFRow hsRow = sheet.getRow(rownum);
                    hsRow.getCell(4).setCellValue((String)hsMap.get("name"));
                    hsRow.getCell(5).setCellValue((Long)hsMap.get("setmeal_count"));
                    hsRow.getCell(6).setCellValue(((BigDecimal)hsMap.get("proportion")).doubleValue());
                    hsRow.getCell(7).setCellValue((String)hsMap.get("remark"));
                    rownum++;
                }
            }
            //6.通过输出流往浏览器写excel文件
            OutputStream out = response.getOutputStream();
            //设置文件类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//xlsx
            //设置文件名称
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            xssfWorkbook.write(out);
            //7.释放资源
            out.flush();
            out.close();
            xssfWorkbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 使用jxls-core技术到处excel报表
     * @return
     */
    @RequestMapping(value = "/exportBusinessReport", method = RequestMethod.GET)
    public Result exportBusinessReportByJXLS_CORE(HttpServletRequest request, HttpServletResponse response){
        try {
            //获取报表需要数据
            Map map = reportService.getBusinessReportData();
            //获取文件路径
            String templatePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template_jxls_core.xlsx";
            //生成excel对象
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(new File(templatePath)));
            //jxls-core对象,
            XLSTransformer transformer = new XLSTransformer();
            //xssfWorkbook:excel模板对象  map:模板需要的数据map
            transformer.transformWorkbook(xssfWorkbook, map);
            //输出流输出excel
            OutputStream out = response.getOutputStream();
            //设置文件类型
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//xlsx
            //设置文件名称
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            xssfWorkbook.write(out);
            //释放资源
            out.flush();
            out.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    /**
     * 导出PDF格式的运营数据
     */
    @RequestMapping(value = "/exportBusinessReportPDF",method = RequestMethod.GET)
    public Result exportBusinessReportPDF(HttpServletRequest request, HttpServletResponse response) {
        try {
            //查询需要的运营数据
            Map map = reportService.getBusinessReportData();
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");
            //模板文件路径
            String oldPath = request.getSession().getServletContext().getRealPath("template")+File.separator+"health_business.jrxml";
            //编译后文件路径
            String newPath = request.getSession().getServletContext().getRealPath("template")+File.separator+"health_business.jasper";
            //编译模板文件
            JasperCompileManager.compileReportToFile(oldPath, newPath);
            //填充数据,map中的数据为普通数据,list<Map>为JavaBean数据循环插入
            JasperPrint jasperPrint = JasperFillManager.fillReport(newPath,map,new JRBeanCollectionDataSource(hotSetmeal));
            //设置文件名和响应信息
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            //通过输出流直接响应给客户端
            JasperExportManager.exportReportToPdfStream(jasperPrint,response.getOutputStream());
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
